package huoye.shops.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Created by who on 2018/8/25.
 */

public class MapFile {

    public static Map<String,RequestBody> filesToMap(String key, String[] filePaths){
        if (filePaths==null)return null;
        Map<String,RequestBody> map = new HashMap<>();
        for (String filePath : filePaths) {
            File file = new File(filePath);
            RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"),file);
            map.put(key,body);
        }
        return map;
    }

    public static List<MultipartBody.Part> filesToList(String key, String[] filePaths){
        if (filePaths==null) return null;
        List<MultipartBody.Part> list = new ArrayList<>();
        for (String filePath : filePaths) {
            File file = new File(filePath);
            RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"),file);
            MultipartBody.Part part = MultipartBody.Part.createFormData(key, file.getName(), body);
            list.add(part);
        }
        return list;
    }

    //多个文件上传
    public static MultipartBody.Part[] filesToArray(String key,String[] filePaths){
        if (filePaths==null)return null;
        MultipartBody.Part[] parts = new MultipartBody.Part[filePaths.length];
        for (int i=0,len = filePaths.length;i<len;i++) {
            File file = new File(filePaths[i]);
            RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"),file);
            parts[i] = MultipartBody.Part.createFormData(key, file.getName(), body);
        }
        return parts;
    }

    //单个文件上传
    public static MultipartBody.Part imageFileToRequestBody(String filePath){
        File file = new File(filePath);
        RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"),file);
        return MultipartBody.Part.createFormData("portrait", file.getName(), body);
    }

   // 表单没文件提交
    public static RequestBody stringToRequestBody(String s){
        return RequestBody.create(MediaType.parse("multipart/form-data"), s);
    }







    /**
     * hashMap 转化成表单字符串
     * @param map
     * @return
     */
    public static String map2Form(Map<String, String> map) {
        StringBuilder stringBuilder = new StringBuilder();
        if(map == null) {
            return stringBuilder.toString();
        } else {
            for (Map.Entry<String, String> entry:
                    map.entrySet() ) {
                stringBuilder.append(entry.getKey())
                        .append("=")
                        .append(entry.getValue())
                        .append("&");
            }
            return stringBuilder.substring(0, stringBuilder.length() - 1);
        }
    }



}
